<?php

namespace App\Models\Basic;

use App\Models\BaseModel;
use Illuminate\Support\Facades\Auth;

class Region extends BaseModel
{

    /**
     * @var string
     *
     * @author lql
     */
    protected $table = 'regions';
    protected $fillable = [
        'title', 'code', 'description', 'rank', 'state', 'charged_by', 'created_by', 'updated_by', 'data_scope'
    ];
    public $sorters = ['rank', 'created_at'];
    public $params = ['title', 'code'];

    public function chargedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'charged_by');
    }

    public function provinces()
    {
        return $this->hasMany('App\Models\Basic\RegionProvince', 'region_id');
    }

    /**
     * 添加大区
     * @param $data
     * @return mixed
     */
    public function addRegion($data)
    {
        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['data_scope'] = $this->getDataScope();

        return $this->create($data);
    }

    /**
     * 编辑大区
     * @param $data
     * @param $id
     * @return null
     */
    public function editRegion($data, $id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        $data['updated_by'] = Auth::id();

        return $model->updateOrCreate(['id' => $id], $data);
    }

    /**
     * 获取大区全部
     * @return mixed
     */
    public function getRegionListAll()
    {
        return $this->where('state', 1)->orderBy('rank', 'asc')->get(['id', 'title', 'code']);
    }

    public function getRegionList($limit, $sorter, $search, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if ($defaultSorter == 'asc') {
            $model = $this->orderBy('rank', $defaultSorter);
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }

        $model->select(['id', 'title', 'code', 'description', 'rank', 'state', 'charged_by', 'created_at'])->with('chargedBy:id,username');

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'code':
                case 'title':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
            }
        }

        return $model->paginate($perPage)->toArray();
    }

    /**
     * 获取大区树状结构
     * @return array
     */
    public function getRegionTree()
    {
        $model = $this->with('provinces:id,region_id,title,code')
            ->where('state', 1)
            ->whereHas('provinces', function($provinces) {
                $provinces->where('state', 1);
            })
            ->get(['id', 'title'])
            ->toArray();

        return $model;
    }
}
